<?php 
	require_once("init.php"); 
?>

<?php
	$errorMessage = ""; 
	if (isset($_POST["username"]) && isset($_POST["password"])) {
		if (strlen($_POST["username"]) == 0 || strlen($_POST["password"]) == 0) {
			$errorMessage = "Please enter your username and password.";
		} else {
			// Check if user exists
			$qCheckUser = mysql_query("
				SELECT *
				FROM users 
				WHERE username = '".$_POST["username"]."'
					AND password = '".$_POST["password"]."'
			");
			if (mysql_num_rows($qCheckUser) == 0) {
				$errorMessage = "The username and password you have entered could not be found.";
			} else {
				while ($row = mysql_fetch_array($qCheckUser)) {
					$_SESSION["userId"] = $row["userId"];
					$_SESSION["username"] = $row["username"];
					break;
				}
?>
<form id="loginSuccess" class="dialog" method="post" target="_self" action="redirect.php?url=index.php">
	<fieldset>
    <h1>You are now signed in!</h1>
    <p align="center"><input class="submit" type="submit" name="submit" value="Continue" /></p>
  </fieldset>
</form>
<?php
			}
		}
	}
	
	if (!isset($_SESSION["username"])) {
?>
<form id="loginForm" class="dialog" method="post" action="login.php">
  <fieldset>
    <h1>Account Sign In</h1>
    <a class="button leftButton" type="cancel">Cancel</a>
    <label>Username:</label>
    <input type="text" name="username" maxlength="20" <?php if (isset($_POST["username"])) print "value=\"".$_POST["username"]."\"" ?> />
    <label>Password:</label>
    <input type="password" name="password" maxlength="20" />
    <p class="error" align="center"><?php print $errorMessage; ?></p>
    <p align="center"><input class="submit" type="submit" name="submit" value="Sign In" /></p>
  </fieldset>
</form>
<?php
	}
?>